using System;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace ProjectSurvival
{
    public partial class CameraController : ViewController
    {
        Vector2 mTargetPosition = Vector2.zero;
        Vector3 mCurrentPosition = Vector3.zero;


        private bool isShake = false;
        [SerializeField]private float shakeTime = 0.5f;
        float currentTime = 0;

        public static CameraController instance;
        public static Transform Lb => instance.LB;
        public static Transform Rt => instance.RT;

        private void Awake()
        {
            if (instance == null)
            {
                instance = this;
            }
        }

        private void OnDestroy()
        {
            instance = null;
        }

        public void ShakeCamera()
        {
            instance.isShake = true;
        }

        private void Update()
        {
            if (Player.Instance)
            {
                mTargetPosition = Player.Instance.transform.position;
                Vector3 newPosition = Vector2.Lerp(transform.position, mTargetPosition,
                    1 - Mathf.Exp(-Time.deltaTime * 20));
                transform.position = new Vector3(newPosition.x, newPosition.y, transform.position.z);

                mCurrentPosition = transform.position;
                //吃到炸弹后屏幕震动
                if (isShake)
                {
                    
                    currentTime += Time.unscaledDeltaTime;
                    float shakeAmplitude = Mathf.Lerp(0.2f, 0f, currentTime / shakeTime);
                    
                    transform.position = new Vector3(mCurrentPosition.x + Random.Range(-shakeAmplitude, shakeAmplitude),
                        mCurrentPosition.y + Random.Range(-shakeAmplitude, shakeAmplitude), transform.position.z);
                    if (shakeTime < currentTime)
                    {
                        isShake = false;
                        currentTime = 0;
                    }
                }

                // mTargetPosition = Player.Instance.transform.position;
                // transform.PositionX(
                //     (1.0f - Mathf.Exp(-Time.deltaTime * 20)).Lerp(transform.position.x, mTargetPosition.x));
                // transform.PositionY(
                //     (1.0f - Mathf.Exp(-Time.deltaTime * 20)).Lerp(transform.position.y, mTargetPosition.y));
            }
        }
    }
}